import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import CultureManagement from '../views/CultureManagement.vue'
import TutorialManagement from '../views/TutorialManagement.vue'
import NewsManagement from '../views/NewsManagement.vue'
import BannerManagement from '../views/BannerManagement.vue'
import UserManagement from '../views/UserManagement.vue'
import Profile from '../views/Profile.vue'

import SystemSettings from '../views/SystemSettings.vue'
import ContentReview from '../views/ContentReview.vue'
import SystemLogs from '../views/SystemLogs.vue'
import Login from '../views/Login.vue'
import MainLayout from '../views/MainLayout.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: MainLayout,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Home',
        component: Home
      },
      {
        path: '/culture',
        name: 'CultureManagement',
        component: CultureManagement
      },
      {
        path: '/tutorials',
        name: 'TutorialManagement',
        component: TutorialManagement
      },
      {
        path: '/news',
        name: 'NewsManagement',
        component: NewsManagement
      },
      {
        path: '/banners',
        name: 'BannerManagement',
        component: BannerManagement
      },
      {
        path: '/users',
        name: 'UserManagement',
        component: UserManagement
      },
      {
        path: '/profile',
        name: 'Profile',
        component: Profile
      },
      {
        path: '/settings',
        name: 'SystemSettings',
        component: SystemSettings
      },
      {
        path: '/review',
        name: 'ContentReview',
        component: ContentReview
      },
      {
        path: '/logs',
        name: 'SystemLogs',
        component: SystemLogs
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 检查token是否有效（简单检查格式和过期时间）
function isTokenValid(token) {
  if (!token) return false
  
  try {
    // 解析JWT token
    const parts = token.split('.')
    if (parts.length !== 3) return false
    
    const payload = JSON.parse(atob(parts[1]))
    const currentTime = Math.floor(Date.now() / 1000)
    
    // 检查是否过期
    return payload.exp && payload.exp > currentTime
  } catch (error) {
    console.error('Token解析失败:', error)
    return false
  }
}

// 清理无效的token和用户信息
function clearInvalidAuth() {
  localStorage.removeItem('token')
  localStorage.removeItem('userInfo')
}

// 添加路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 剪纸文化展示平台管理系统`
  } else {
    document.title = '剪纸文化展示平台管理系统'
  }
  
  // 如果访问的路由需要认证
  if (to.meta.requiresAuth !== false) {
    // 没有token或token无效，跳转到登录页
    if (!token || !isTokenValid(token)) {
      if (token && !isTokenValid(token)) {
        // token无效，清除本地存储
        clearInvalidAuth()
        console.warn('Token已过期，自动清理')
      }
      next({
        path: '/login',
        query: to.path !== '/' ? { redirect: to.fullPath } : {}
      })
    } else {
      next()
    }
  } else {
    // 访问不需要认证的页面（如登录页）
    // 如果已有token且token有效且访问登录页，重定向到目标页面或首页
    if (token && isTokenValid(token) && to.path === '/login') {
      const redirect = to.query.redirect || '/'
      next(redirect)
    } else {
      next()
    }
  }
})

export default router